package com.hczt.fire.server.config.sercurity.util;

import com.alibaba.fastjson.JSON;
import com.hczt.fire.server.config.sercurity.StudentEntity;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 精诚所至，金石为开。
 * 石の上にも三年;陽気の発する所金石亦透る。
 * Faith moves mountains.
 *
 * @author marvin.ma
 * @create 2017-11-30 6:42
 * @desc 3DES加解密工具
 **/
public class DES3Util {

    public static final String DESKEY = "DE76E3EC39801CEEE0440025";

    public static final String CHAR_SET = "UTF-8";

    public DES3Util() {
    }

    /**
     * 字符串加密
     * @Auther: marvin.mma
     * @Date: 2017/11/30 7:21
     * @return   
     */
    public synchronized static String encrypt(String content) {
        try {
            return encrypt(content, DESKEY, CHAR_SET);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
    }

    public static String toDES(String json) {

        return encrypt("comSMAPPcom" + "|" + json + "|" + System.currentTimeMillis());
    }

    /**
     * 加密内容
     * @param content 	加密内容
     * @param desKey  	3DES KEY
     * @param charset  	字符集
     *
     * @Auther: marvin.mma
     * @Date: 2017/11/30 6:45
     * @return   
     */
    public static String encrypt(String content, String desKey, String charset) throws Exception {
        try {
            if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {
                throw new Exception("3des key's length must be 24");
            }
            if(StringUtils.isEmpty(content)) {
                return "";
            }
            SecretKeySpec key = new SecretKeySpec(desKey.getBytes(charset), "DESede");
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte [] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return BASE64Encoder.encode(encryptBytes);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 解密内容
     * @param content		解密内容
     * @param desKey		3des key
     * @param charset		字符集
     * @Auther: marvin.mma
     * @Date: 2017/11/30 6:46
     * @return   
     */
    public static String decrypt(String content, String desKey, String charset) throws Exception {
        try {

            if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {
                throw new Exception("3des key's length must be 24");
            }
            if(StringUtils.isEmpty(content)) {

                return "";
            }

            byte [] decryptBytes = null;
            decryptBytes = new BASE64Decoder().decodeBuffer(content);
            //System.out.println("decryptBytes:"+decryptBytes);
            SecretKeySpec key = new SecretKeySpec(desKey.getBytes(charset), "DESede");
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(decryptBytes), charset);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 字符串解密
     * @Auther: marvin.mma
     * @Date: 2017/11/30 7:22
     * @return   
     */
    public static String decrypt(String content) {
        try {
            return decrypt(content, DESKEY, CHAR_SET);
        }
        catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *  SHA1 加密
     * @Auther: marvin.mma
     * @Date: 2017/11/30 6:47
     * @return   
     */
    public static String SHA1(String decrypt) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 测试
     * @Auther: marvin.mma
     * @Date: 2017/11/30 7:19
     * @return   
     */
    public static void main(String args[]) {
        StudentEntity student = new StudentEntity();
        student.setAge(20);
        student.setName("xinxin");
        String des = encrypt(JSON.toJSONString("name=xinxin&age=23"));
        System.out.println("加密后：" + des);

        String decryptStr = decrypt(des);
        System.out.println("解密后：" + decryptStr);

        System.out.println("加密后：" + encrypt(JSON.toJSONString("name=marvin&age=28")));
        System.out.println("解密后：" + decrypt("nSQf+6WcFcjFcnbevVV7biDK+DSqw+AIL"));
    }
}
